<template>
	<ckeditor ref="editor" :config="config" v-model="model" @namespaceloaded="onNamespaceLoaded" @ready="onEditorReady"
		style="width:100%;height: 100%;" editor-url="/static/js/ckeditor/ckeditor.js"
		v-if="!!routePath&&routePath==routePath2">
	</ckeditor>
</template>

<script>
	import config from "@/common/config.js";
	import common from "@/common/common.js";
	import fileHelper from '@/common/components/fileHelper.js';

	export default {
		name: 'editor',
		mixins: [common.baseVM],
		components: {},
		data() {
			return {
				model: "",
				name: "",
				//利用路由不一样,来展示富文本和销毁富文本
				routePath: ""
				// editor: null
			}
		},
		computed: {
			routePath2() {
				return this.$route.path;
			}
		},
		watch: {
			model(n, o) {
				this.$emit("input", n);
			},
			value(n, o) {
				this.model = n;
			},
			$route(n, o) {
				// console.log("$route", n);
				// if (!!this.name) {
				//     var obj = CKEDITOR.instances[this.name];
				//     if (!!obj) {
				//         obj.destroy();
				//         console.log("$route2", this.name);
				//     }
				// }
			}
		},
		props: {
			config: {
				type: Object,
				default: function() {
					var editorConfig = {
						language: 'zh-cn', //english
						toolbarGroups: [{
								name: 'document',
								groups: ['mode'] //'mode', 'document', 'doctools'
							},
							{
								name: 'styles',
								groups: ['styles']
							},
							{
								name: 'colors'
							},
							{
								name: 'clipboard',
								groups: ['clipboard', 'undo']
							},
							// {
							//     name: 'editing',
							//     groups: ['find', 'selection', 'spellchecker', 'editing']
							// },
							{
								name: 'forms',
								groups: ['forms']
							},
							{
								name: "justify",
								groups: ["AlignLeft", "AlignCenter", "AlignRight", "AlignJustify"]
							},
							{
								name: 'basicstyles',
								groups: ['basicstyles', 'cleanup']
							},
							{
								name: 'paragraph',
								groups: ['list', 'indent', 'blocks', 'align', 'bidi', 'paragraph']
							},
							{
								name: 'links',
								groups: ['links']
							},
							// {
							//     name: 'myImage',
							//     groups: ['myImage']
							// },
							{
								name: 'insert',
								groups: ['insert']
							},

							{
								name: 'tools',
								groups: ['tools', 'preview', 'colorbutton']
							}
						],
						// Remove the redundant buttons from toolbar groups defined above.
						removeButtons: 'Save,NewPage,DocProps,Templates,ExportPdf,Checkbox,Radio,TextField,Textarea,Select,Button,ImageButton,HiddenField,Strike,Subscript,Superscript,Anchor,Specialchar,ShowBlocks',

						filebrowserImageBrowseLinkUrl: "/#/System/SysFileListChoice?onlyImage=true",
						filebrowserImageBrowseUrl: "/#/System/SysFileListChoice?onlyImage=true",
						extraPlugins: "uploadimage,justify,preview,colorbutton,colordialog",
						// 后端处理上传逻辑返回json数据,包括uploaded 上传的字节数 和url两个字段
						uploadUrl: config.webapiUrl + `/api/System/SysFileAdd`,
						// filebrowserImageUploadUrl: "/#/",
						// filebrowserUploadUrl: "/#/",
						// fontSize: {
						//     options: [8, 9, 10, 11, 12, 'default', 14, 16, 18, 20, 22, 24, 26, 28, 36, 44, 48, 72],
						// },
						// highlight: {
						//     options: [{
						//             model: 'blackPen',
						//             class: 'pen-black',
						//             title: '黑色',
						//             color: 'var(--ck-highlight-pen-black)',
						//             type: 'pen'
						//         },
						//         {
						//             model: 'redPenPen',
						//             class: 'pen-red',
						//             title: '红色',
						//             color: 'var(--ck-highlight-pen-red)',
						//             type: 'pen'
						//         },
						//     }
						// },
					};
					return editorConfig;
				}
			},
			ready: {
				type: Function,
				default: () => {}
			},
			value: {
				type: String,
				default: ""
			}
		},
		beforeDestroy() {
			// console.log("beforeDestroy", this.name);
			// if (!!this.name) {
			//     var obj = CKEDITOR.instances[this.name];
			//     if (!!obj) {
			//         obj.destroy();
			//         console.log("beforeDestroy2", this.name);
			//     }
			// }
		},
		created() {
			this.routePath = this.$route.path;
		},
		methods: {
			init() {
				//console.log("editor init");
			},

			onNamespaceLoaded(editor) {
				//console.log(editor);
			},
			onEditorReady(editor) {
				// this.editor = editor;
				if (editor != null) {
					this.name = editor.name;
				}
				this.$nextTick(() => {
					if (!this.model && !!this.value) {
						this.model = this.value;
					}
				});
				editor.on('fileUploadRequest', (evt) => {
					//evt.data.requestData.foo = 'bar';
					var url = editor.config.uploadUrl;
					evt.data.requestData.foo = 'bar';
					evt.stop();
					var loader = evt.data.fileLoader;
					//loader.uploadTotal = 1;
					fileHelper.compressedBase64(loader.data, loader.file.type).then((compress) => {
						//console.log(loader.data.length, data.length);
						this.post(url, {
							SysFileName: loader.fileName,
							FilePath: compress.base64,
							NoAddMore: true
						}).then(data => {
							evt.cancel();
							//loader.uploadTotal = loader.uploaded = loader.total;
							loader.status = "uploaded";
							var filePath = this.commonUrl(data.Result.FilePath);
							loader.url = filePath;
							loader.responseData = {
								height: compress.height,
								width: compress.width
							};
							loader.update();
						}).catch(e => {
							evt.cancel();
							loader.update();
							loader.abort();
						});
					});
					//console.log("onNamespaceLoaded.fileUploadRequest", url, evt);
				});
				editor.on('fileUploadResponse', function(evt) {
					//console.log("onNamespaceLoaded.fileUploadResponse", evt);
					evt.stop();
					return;
					// Get XHR and response.
					// var data = evt.data;
					// var xhr = data.fileLoader.xhr;
					// var response = xhr.responseText.split('|');
					// if (response[1]) {
					//     // An error occurred during upload.
					//     data.message = response[1];
					//     e.cancel();
					// } else {
					//     data.url = response[0];
					// }
				});
				editor.on('insertHtml', (evt) => {
					//console.log("insertHtml", evt);
				});
				editor.on('afterInsertHtml', (evt) => {
					//console.log("afterInsertHtml", evt);
				});
				editor.on('insertElement', (evt) => {
					//console.log("insertElement", evt);
				});
				this.ready(editor);
			},

			//设置editor的html文本内容
			setContent(data) {
				this.model = data;
				//this.$refs.editor.instance.setData(data)
			},
			//获取editor的html文本内容
			getContent() {
				//return this.$refs.editor.instance.getData()
				return this.model;
			},
			//在鼠标处插入指定的html
			insertHtml(html) {
				console.log("insertHtml", html);
				this.$refs.editor.instance.insertHtml(html)
			},
			//执行editor内置的command
			execCommand(command) {
				this.$refs.editor.instance.execCommand(command)
			},
			//将editor设为readonly的
			setReadonly(readonly) {
				this.$refs.editor.instance.setReadOnly(readonly)
			},
			//判断是否是readonly的
			isReadonly() {
				return this.$refs.editor.instance.readOnly
			},
			//disable/enable指定的command
			setDisable(command, disable) {
				if (disable) {
					this.$refs.editor.instance.commands[command].enable()
				} else {
					this.$refs.editor.instance.commands[command].disable()
				}
			},
			//获取指定的command，比如'source'
			getCommand(command) {
				return this.$refs.editor.instance.commands[command]
			}
		}
	}
</script>
